<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="chrome=1">
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
		<link rel="icon" href="./favicon.ico">
		<link rel="stylesheet" href="./css/index.css">
		<title>高德地图框选示例</title>
		<script>
			window._AMapSecurityConfig = {
				securityJsCode: '你的秘钥' // 秘钥，根据经纬度查询地址时用到
			}
		</script>
		<!-- 高德地图 -->
		<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你的key值&plugin=AMap.MouseTool"></script> 
	</head>
	<body>
		<div class="content">
			<div class="fix">
				<select onchange="drawTypeChange(event)">
					<option value="rectangle">框选</option>
					<option value="circle">圆选</option>
					<option value="polygon">多边形</option>
				</select>
				<div class="checkbox">
					<span>开启绘制</span>
					<input type="checkbox" onchange="openChange(event)">
				</div>
				<button class="btn" onclick="clearOverlays()">清除</button>
			</div>
			<div class="float-window">
				<div style="padding: 10px;text-align: center;">
					已选点位
					(<span id="num">0</span>/500)
				</div>
				<ul class="list" id="ul"></ul>
			</div>
			<div id="map"></div>
		</div>
		<script>
			var map = null, // 地图
					mouseTool = null, // 鼠标绘制工具
					overlays = [], // 覆盖物
					pointList = [], // 全部随机点
					markerList = [], // 标记点
					selectedData = [], // 已选择数据
					open = false, // 关闭/开启框选
					drawType = 'rectangle' // 绘制类型，rectangle：框选，circle：圆选，polygon：多边形选择
					
			var ul = document.getElementById('ul')
			var sp = document.getElementById('num')
			// 默认图标
			var icon = new AMap.Icon({
				size: new AMap.Size(19, 33),    // 图标尺寸
				image: './img/mark_bs.png',  // Icon的图像
				// imageOffset: new AMap.Pixel(0, -10),  // 图像相对展示区域的偏移量
				imageSize: new AMap.Size(19, 33)   // 根据所设置的大小拉伸或压缩图片
			});
			// 选中图标
			var icon2 = new AMap.Icon({
				size: new AMap.Size(19, 33),    // 图标尺寸
				image: './img/mark_rs.png',  // Icon的图像
				imageSize: new AMap.Size(19, 33),   // 根据所设置的大小拉伸或压缩图片
				selected: true
			});
			window.onload = function(){
				map = new AMap.Map('map', {
					resizeEnable: true, // 是否监控地图容器尺寸变化
					zoom: 8
				})
				// 通过AMap.plugin方法按需引入插件
				AMap.plugin(['AMap.Scale'], () => {
					map.addControl(new AMap.Scale())
				})
				// map.setZoomAndCenter(8, [120.142201, 30.320152])  // 设置显示级别及中心
				// map.on('click', onMapClick) // 添加地图点击事件
				map.clearMap() // 清除所有的覆盖物信息
				map.on('complete', function(){ // 地图加载完成
					console.log('地图加载完成')
				})
				mouseTool = new AMap.MouseTool(map)
				addTestData()
			}
			// 测试数据
			function addTestData() {
				for (var i = 0; i < 500; i++) {
					// 随机经纬度
					var lng = Math.random() * 40 + 85
					var lat = Math.random() * 30 + 21
					pointList.push([lng, lat])
					var marker = new AMap.Marker({
						position: new AMap.LngLat(lng, lat),
						icon: icon,
						name: '点' + i
					})
					marker.on('click', function(e){
						var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -33), anchor: 'bottom-center' })
						infoWindow.setContent(e.target.w.name)
						infoWindow.open(map, e.target.w.position)
					})
					markerList.push(marker)
					map.add(marker)
				}
			}
			// 类型选择
			function drawTypeChange(e){
				closeTool()
				drawType = e.target.value
				if(open){
					draw()
				}
			}
			// 绘制开启/关闭
			function openChange(e){
				closeTool()
				open = e.target.checked
				if(open){
					draw()
				}else{
					mouseTool.close(true)
				}
			}
			// 绘制
			function draw(){
				mouseTool = new AMap.MouseTool(map) // 重新构造工具，避免多个事件触发
				mouseTool[drawType]({
				  fillColor: '#ffffff',
				  fillOpacity: 0.5,
				  strokeOpacity: 0.5,
				  strokeColor: 'blue',
					zIndex: 1000
				})
				mouseTool.on('draw', function(e){
					if(overlays.length){
						map.remove(overlays)
						overlays = []
					}
					overlays.push(e.obj);
					selectedData = []
					var bounds = e.obj.getBounds()
					var path = []
					if (e.obj.CLASS_NAME === 'AMap.Marker') { // 点
					  path.push(e.obj.getPosition())
					} else {
					  var southWest = bounds.getSouthWest()
					  var northEast = bounds.getNorthEast()
					  if (southWest.equals(northEast)) {
					    return
					  }
					  path = e.obj.getPath()
					}
					var num = 0
					pointList.forEach((point, i) => {
					  const isPointInRing = AMap.GeometryUtil.isPointInRing(point, path) // 判断是否在几何图形内
						var mIcon = markerList[i].getIcon()
					  if (isPointInRing) {
							selectedData.push(markerList[i])
							markerList[i].setIcon(icon2)
							num += 1
					  } else if(mIcon.w.selected) {
							markerList[i].setIcon(icon)
						}
					})
					console.log(selectedData)
					var lis = ''
					selectedData.forEach(item =>{
						// var li = `<li>${item.w.name}</li>`
						var li = '<li>' + item.w.name + '</li>'
						lis += li
					})
					ul.innerHTML = lis
					sp.innerText = num
				}) 
			}
			// 关闭，并清除覆盖物
			function closeTool(){
				mouseTool.close(true) // 关闭，并清除覆盖物
				clearOverlays()
			}
			// 清除覆盖物
			function clearOverlays(){
				map.remove(overlays)
				markerList.forEach(item =>{
					if(item.getIcon().w.selected){
						item.setIcon(icon)
					}
				})
				overlays = []
				ul.innerHTML = ''
				sp.innerText = 0
			}
			// 地图点击事件
			function onMapClick (e) {
				var markerPoint = [e.lnglat.lng, e.lnglat.lat]
				AMap.plugin('AMap.Geocoder', () => {
					var GeocoderOptions = { city: '全国' }
					var geocoder = new AMap.Geocoder(GeocoderOptions)
					geocoder.getAddress(markerPoint, (status, result) => { // 根据经纬度查询地址
						if (status === 'complete' && result.info === 'OK') {
							console.log(result.regeocode.formattedAddress)
							map.clearMap() // 清除所有的覆盖物信息
							var marker = new AMap.Marker({
								position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat), // 添加经纬度
								address: result.regeocode.formattedAddress
							})
							marker.on('click', function(e){
								var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -33), anchor: 'bottom-center' })
								infoWindow.setContent('地址：' + e.target.w.address + '<br>' + 'lng：' + e.lnglat.lng + ' lat：' + e.lnglat.lat)
								infoWindow.open(map, e.target.w.position)
							})
							map.add(marker)
						}else{
							alert('查询地址失败！')
						}
					})
				})
			}
		</script>
	</body>
</html>
